package com.example.flashsales.controller;

import com.example.flashsales.Factory;
import com.example.flashsales.Tools.NumberUtil;
import com.example.flashsales.Tools.RedisUtils;
import com.example.flashsales.Tools.TokenTool;
import com.example.flashsales.entity.Result;
import com.example.flashsales.entity.dto.*;
import com.example.flashsales.entity.pojo.Store;
import com.example.flashsales.entity.vo.OrderCarDetailsVo;
import com.example.flashsales.entity.vo.StoreVo;
import com.example.flashsales.entity.vo.UserVo;
import com.example.flashsales.entity.vo.ZhekouVo;
import com.example.flashsales.service.impl.StoreServiceImpl;
import com.example.flashsales.service.impl.UserServiceImpl;
import com.example.flashsales.service.impl.ZhekouServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserServiceImpl userService;

    @Autowired
    StoreServiceImpl storeService;

    @Autowired
    ZhekouServiceImpl zhekouService;

//    @Autowired
//    Factory factory;
    Factory factory = Factory.getFactory();


    @Autowired
    private RedisUtils redisUtils;

    /**
     *
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody UserDto userDto){
        if (userDto == null){
            return Result.error("数据不能为空");
        }
        if(userDto.getCode() == null || userDto.getCode().equals("")){
            userDto.setStoreId(0);
        }else {
            final Store store = storeService.viewStoreMessageByInviteCode(userDto.getCode());
            if (store == null){
                return Result.error("注册失败,店家不存在");
            }
            userDto.setStoreId(store.getId());
        }
        if (!NumberUtil.isPhone(userDto.getPhone())){
            return Result.error("请输入正确的手机号");
        }
        final String register = userService.register(userDto);
        if (register.equals("注册成功")){
            return Result.ok(register);
        }
        return Result.error(register);
    }




    /**
     * 通过电话号码和密码登录,返回的时候在响应头里面设置Token
     *
     * @param userDto             （phone,password）
     * @param httpServletResponse
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/loginByPassword")
    @ResponseBody
    public Result loginByPassword(@RequestBody UserDto userDto, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET");
        httpServletResponse.addHeader("Access-Control-Expose-Headers", "Token");
        if (userDto == null || userDto.getPassword().equals("") || userDto.getPassword() == "" || userDto.getPhone().equals("") || userDto.getPhone() == "") {
            log.error("用户登入时->账号或密码为空");
            return Result.error("账号密码不能为空");
        }
        final UserVo userVo = userService.loginByPassword(userDto.getPhone(), userDto.getPassword());
        if (userVo == null) {
            log.error("用户登入时->账号或密码错误");
            return Result.error("账号密码错误");
        }
        if (userVo.getState() != 0){
            return Result.error("你已被封号");
        }
        //生成Token
        Map<String, String> map = new HashMap<>();
        map.put("id", userVo.getId() + "");
        map.put("phone", userVo.getPhone());
        final Date date = new Date();
        final String token = TokenTool.createToken(map);
        httpServletResponse.setHeader("Token", token);
        log.info("用户登录时->登录成功");
        final String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        userVo.setData(format);
        factory.addUser(userVo);
        return Result.ok("登录成功").setData(userVo);
    }


    /**
     * 退出登录
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @GetMapping("/logout")
    public Result logout(HttpServletRequest httpServletRequest){
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        factory.getOnlineUsers().remove(id);
        return Result.ok("退出成功");
    }

    /**
     * 用户查看自己的信息
     *
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @GetMapping("/viewUserMessage")
    public Result viewUserMessage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
//        System.out.println(httpServletRequest.getAttribute("id"));
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        final UserVo userVo = userService.viewUserMessage(id);
        if (userVo == null) {
            log.error("用户查看自己的信息时->用户不存在");
            return Result.error("用户不存在");
        }
        Result result = Result.ok("查看成功");
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        userVo.setData(simpleDateFormat.format(date));
        result.setData(userVo);
        return result;
    }


    /**
     * 通过原密码修改
     *
     * @param newPassword
     * @param oldPassword
     * @param httpServletResponse
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @GetMapping("/modifyPasswordByPassword")
    public Result modifyPasswordByPassword(String newPassword, String oldPassword, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        String str = userService.modifyPasswordByPassword(id, oldPassword, newPassword);
        if (str.equals("修改成功")) {
            log.error("用户修改密码时->" + str);
            return Result.ok(str);
        }
        log.error("用户修改密码时->" + str);
        return Result.error(str);

    }


    /**
     * 查看用户余额
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @GetMapping("/viewUserMoney")
    public Result viewUserMoney(HttpServletRequest httpServletRequest){
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        final double v = userService.viewUserMoney(id);
        return Result.ok("查看成功").setData(v);
    }


    /**
     * 用户通过余额支付
     * @param httpServletRequest
     * @param money
     * @param orderId
     * @return
     */
    @ResponseBody
    @GetMapping("/payMoneyByBalance")
    public Result payMoneyByBalance(HttpServletRequest httpServletRequest,double money,long orderId){
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        final String s = userService.payMoneyByBalance(id, money, orderId);
        if (s.equals("购买成功")){
            return Result.ok(s);
        }
        return Result.error(s);
    }


    /**
     * 按类型查看流水纪录 和时间
     * @param httpServletRequest
     * @param page
     * @param num
     * @param state 状态  0-支付，1-退款 2全部
     * @return
     */
    @GetMapping("/viewCostRecord")
    @ResponseBody
    public Result viewCostRecord(HttpServletRequest httpServletRequest,Integer page,Integer num,Integer state,Date qDate,Date hDate){
        if (num == null || page == null || page <= 0 || num < 0){
            return Result.error("参数异常");
        }
        if (state != 0 && state != 1 && state != 2){
            return Result.error("类型不存在");
        }
        System.out.println(httpServletRequest.getAttribute("id"));
        final Object id = httpServletRequest.getAttribute("id");
        final long i = Integer.parseInt(id + "");
        System.out.println(i);
        final Map<String, Object> map = userService.viewCostRecord(i, state, page, num, qDate, hDate);
        return Result.ok("查看成功").setData(map);
    }


    /**
     * 领取卷
     * @param httpServletRequest
     * @param Zid
     * @return
     */
    @ResponseBody
    @GetMapping("/getVolume")
    public Result getVolume(HttpServletRequest httpServletRequest,Long Zid){
        final int id = Integer.parseInt((httpServletRequest.getAttribute("id") + ""));
        final List<ZhekouVo> zhekouVos = zhekouService.viewVolume(null, null, null, null, null, null, Zid, null, null);
        if (zhekouVos == null || zhekouVos.isEmpty()){
            return Result.error("这张卷不存在");
        }
        if (!zhekouVos.get(0).getState().equals("未领取")){
            return Result.error("这张卷异常不能领取");
        }
        if (zhekouService.drawVoluem(id,Zid)) {
            return Result.ok("领取成功");
        }
        return Result.error("领取失败");
    }

}





